<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="3">
                        <el-form-item label="通道名称">
                            <el-input v-model="queryParams.channelName" placeholder="请输入通道名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="接收者">
                            <el-input v-model="queryParams.receiver" placeholder="请输入接收者" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="消息状态">
                            <el-select v-model="queryParams.status" placeholder="请选择消息状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="失败" :value="0" />
                                <el-option label="成功" :value="1" />
                                <el-option label="发送中" :value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="search-buttons">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleCreate">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="!selectedRows.length"
                        @click="handleBatchDelete">删除</el-button>
                </el-col>
            </el-row>
            <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange"
                style="width: 100%" class="mt-2">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" width="55" align="center" />
                <el-table-column prop="messageTitle" label="消息标题" align="center" />
                <el-table-column prop="messageContent" label="消息内容" align="center" />
                <el-table-column prop="messageTemplate" label="模板内容" align="center" />
                <el-table-column prop="receiver" label="接收人" align="center" />
                <el-table-column prop="messageType" label="消息类型" align="center">
                    <template #default="{ row }">
                        <el-tag>{{ getMessageTypeName(row.messageType) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="channelName" label="通道名称" align="center" />
                <el-table-column prop="sendTime" label="发送时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.sendTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.status)">
                            {{ getStatusName(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="errorMessage" label="失败原因" align="center" />
                <el-table-column label="操作" align="center" width="120">
                    <template #default="{ row }">
                        <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新建消息对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @closed="resetForm">
            <el-form ref="messageForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="消息类型" prop="messageType">
                    <el-select v-model="form.messageType" placeholder="请选择消息类型" @change="handleMessageTypeChange">
                        <el-option v-for="item in messageTypeOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="通道类型" prop="channelId" v-if="form.messageType">
                    <el-select v-model="form.channelId" placeholder="请选择通道类型">
                        <el-option v-for="item in channelTypeOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="模板类型" prop="templateId" v-if="form.channelId">
                    <el-select v-model="form.templateId" placeholder="请选择模板类型" @change="handleTemplateChange">
                        <el-option v-for="item in templateOptions" :key="item.messageTemplateId"
                            :label="item.messageTemplateName" :value="item.messageTemplateId" />
                    </el-select>
                </el-form-item>

                <!-- 原始模板内容显示 -->
                <el-form-item label="原始模板内容" v-if="selectedTemplateContent">
                    <el-input v-model="selectedTemplateContent" type="textarea" :rows="3" readonly placeholder="请先选择模板">
                        <template #append>
                            <el-button @click="copyTemplateContent" type="text">复制</el-button>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 参数配置区域 -->
                <el-form-item label="变量参数配置" v-if="templateParams.length > 0">
                    <div class="params-config">
                        <div class="params-count">共 {{ templateParams.length }} 个变量</div>
                        <div class="params-list">
                            <div v-for="(param, index) in templateParams" :key="index" class="param-item">
                                <div class="param-label">{{ param }}:</div>
                                <el-input v-model="form.params[param]" :placeholder="`请输入${param}的值`" clearable />
                            </div>
                        </div>
                    </div>
                </el-form-item>

                <!-- 预览效果 -->
                <el-form-item label="预览效果" v-if="selectedTemplateContent">
                    <el-input v-model="previewContent" type="textarea" :rows="3" readonly placeholder="预览效果将在此显示">
                        <template #append>
                            <el-button @click="refreshPreview" type="text">刷新预览</el-button>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item label="接收人" prop="receiver">
                    <el-input v-model="form.receiver" placeholder="请输入接收人" />
                </el-form-item>
                <el-form-item label="消息标题" prop="messageTitle">
                    <el-input v-model="form.messageTitle" placeholder="请输入消息标题" />
                </el-form-item>
                <el-form-item label="最终消息内容" prop="messageContent">
                    <el-input v-model="form.messageContent" type="textarea" :rows="4" placeholder="最终消息内容将根据模板和参数自动生成"
                        readonly />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download } from '@element-plus/icons-vue'
import {
    listMessage,
    deleteMessage,
    createMessage,
    exportMessage,
    getChannelTypeDictList,
    getMessageTypeDictCollect,
    getSupplierTypeDictList
} from '@/api/basic/message/query.js'

const showSearch = ref(true)

// 数据状态
const loading = ref(false)
const messageList = ref([])
const total = ref(0)
const selectedRows = ref([])
const messageForm = ref(null)

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    channelName: '',
    receiver: '',
    status: ''
})

// 表单数据
const form = reactive({
    messageType: '',
    channelId: '',
    templateId: '',
    receiver: '',
    messageTitle: '',
    messageContent: '',
    params: {} // 参数对象
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '新建消息'
})

// 字典数据
const channelTypeOptions = ref([]);
const messageTypeOptions = ref([])
const templateOptions = ref([])

// 模板相关数据
const selectedTemplateContent = ref('')
const templateParams = ref([]) // 提取的参数列表
const previewContent = ref('') // 预览内容

// 表单验证规则
const rules = reactive({
    messageType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
    ],
    channelId: [
        { required: true, message: '请选择通道类型', trigger: 'change' }
    ],
    templateId: [
        { required: true, message: '请选择模板类型', trigger: 'change' }
    ],
    receiver: [
        { required: true, message: '请输入接收人', trigger: 'blur' }
    ],
    messageTitle: [
        { required: true, message: '请输入消息标题', trigger: 'blur' }
    ]
})

// 监听参数变化，自动更新预览
watch(() => form.params, (newParams) => {
    refreshPreview()
}, { deep: true })

// 监听模板ID变化
watch(() => form.templateId, (newTemplateId) => {
    if (newTemplateId) {
        handleTemplateChange(newTemplateId)
    }
})

// 格式化时间
const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
}

// 获取状态名称
const getStatusName = (status) => {
    const statusMap = {
        0: '失败',
        1: '成功',
        2: '发送中'
    }
    return statusMap[status] || '未知'
}

// 获取状态标签样式
const getStatusTagType = (status) => {
    const typeMap = {
        0: 'danger',
        1: 'success',
        2: 'warning'
    }
    return typeMap[status] || 'info'
}

// 获取消息类型名称
const getMessageTypeName = (type) => {
    const typeMap = {
        0: '短信',
        1: '邮件',
        2: '钉钉',
        3: '企业微信'
    }
    return typeMap[type] || '未知'
}

// 获取消息列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listMessage(queryParams)
        messageList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取消息列表失败:', error)
        ElMessage.error('获取消息列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = (value) => {
    queryParams.pageNum = value;
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.channelName = ''
    queryParams.receiver = ''
    queryParams.status = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.messageId)
}

// 新建消息
const handleCreate = async () => {
    await loadDictData()
    dialog.visible = true
}

// 加载字典数据 消息类型
const loadDictData = async () => {
    try {
        const res = await getSupplierTypeDictList()
        messageTypeOptions.value = res.data || []
    } catch (error) {
        console.error('加载字典数据失败:', error)
    }
}

// 消息类型变化处理
const handleMessageTypeChange = (val) => {
    form.templateId = ''
    form.channelId = ''
    selectedTemplateContent.value = ''
    templateParams.value = []
    form.params = {}
    previewContent.value = ''

    // 根据消息类型加载模板选项
    loadTemplateOptions(val)
}

// 模板变化处理
const handleTemplateChange = (templateId) => {
    if (!templateId) {
        selectedTemplateContent.value = ''
        templateParams.value = []
        form.params = {}
        previewContent.value = ''
        return
    }

    const selectedTemplate = templateOptions.value.find(item => item.messageTemplateId === templateId)
    if (selectedTemplate) {
        selectedTemplateContent.value = selectedTemplate.messageTemplateContent
        // 提取参数
        extractTemplateParams(selectedTemplate.messageTemplateContent)
    }
}

// 提取模板参数
const extractTemplateParams = (templateContent) => {
    if (!templateContent) {
        templateParams.value = []
        form.params = {}
        return
    }

    // 使用正则表达式提取 #{参数名} 格式的参数
    const paramRegex = /#\{([^}]+)\}/g
    const matches = templateContent.matchAll(paramRegex)
    const params = []

    for (const match of matches) {
        const paramName = match[1]
        if (!params.includes(paramName)) {
            params.push(paramName)
        }
    }

    templateParams.value = params

    // 初始化参数对象
    const newParams = {}
    params.forEach(param => {
        newParams[param] = form.params[param] || ''
    })
    form.params = newParams

    // 更新预览
    refreshPreview()
}

// 刷新预览
const refreshPreview = () => {
    if (!selectedTemplateContent.value) {
        previewContent.value = ''
        form.messageContent = ''
        return
    }

    let preview = selectedTemplateContent.value

    // 替换参数
    templateParams.value.forEach(param => {
        const value = form.params[param] || `#{${param}}`
        preview = preview.replace(new RegExp(`#\\{${param}\\}`, 'g'), value)
    })

    previewContent.value = preview
    form.messageContent = preview
}

// 复制模板内容
const copyTemplateContent = async () => {
    if (!selectedTemplateContent.value) return

    try {
        await navigator.clipboard.writeText(selectedTemplateContent.value)
        ElMessage.success('模板内容已复制到剪贴板')
    } catch (error) {
        console.error('复制失败:', error)
        ElMessage.error('复制失败')
    }
}

// 加载模板选项
const loadTemplateOptions = async (typeValue) => {
    try {
        const responseMessageTypeDictCollect = await getMessageTypeDictCollect({ typeValue });
        const responseChannelTypeDictList = await getChannelTypeDictList({ typeValue });

        templateOptions.value = responseMessageTypeDictCollect.data;
        channelTypeOptions.value = responseChannelTypeDictList.data;
    } catch (error) {
        console.error('加载模板选项失败:', error)
    }
}

// 导出消息
const handleExport = async () => {
    try {
        await exportMessage(queryParams)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 删除消息
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该消息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteMessage(row.messageId)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteMessage(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 重置表单
const resetForm = () => {
    if (messageForm.value) {
        messageForm.value.resetFields()
    }
    Object.assign(form, {
        messageType: '',
        channelId: '',
        templateId: '',
        receiver: '',
        messageTitle: '',
        messageContent: '',
        params: {}
    })
    selectedTemplateContent.value = ''
    templateParams.value = []
    previewContent.value = ''
}

// 提交表单
const submitForm = async () => {
    try {
        await messageForm.value.validate()

        // 构建提交数据
        const submitData = {
            ...form,
            // 将参数对象转换为字符串格式传递给后端
            templateParams: JSON.stringify(form.params)
        }

        await createMessage(submitData)
        ElMessage.success('创建成功')
        dialog.visible = false
        getList()
    } catch (error) {
        if (error && error.fields) {
            ElMessage.warning('请检查表单填写是否正确')
        } else {
            console.error('创建失败:', error)
            ElMessage.error('创建失败')
        }
    }
}

// 初始化
onMounted(() => {
    getList()
    loadDictData()
})
</script>

<style scoped>
.search-card {
    margin-bottom: 20px;
}

.search-buttons {
    text-align: left;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.params-config {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    background-color: #f8f9fa;
}

.params-count {
    font-size: 14px;
    color: #606266;
    margin-bottom: 12px;
    font-weight: 500;
}

.params-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.param-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.param-label {
    width: 100px;
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

:deep(.el-input-group__append) {
    padding: 0 12px;
}
</style>